import traceback


from HslCommunication import AllenBradleyNet # AB cip协议 （写字符串和数组的逻辑和欧姆龙cip不一致）
# plc = AllenBradleyNet('192.168.250.1', 44818)
# plc.Slot = 0
# connect = plc.ConnectServer()
#
# # res = plc.ReadInt16('giPress_VisionStart',1)
# # print(res.Content[0])
# #
# # plc.WriteInt16('giPress_VisionStart',10)
#
# res = plc.ReadString('gstrProgramName',1)
# print(res.Content)
#
# # isok = plc.WriteString('gstrPress_VisionCodeA', '123')
# plc.ConnectClose()



try:
    from plc_client.layer1.abc_client import PLCClientInterface
except:
    from abc_client import PLCClientInterface

class EthIpHslClient(PLCClientInterface): #

    def __init__(self, ip='192.168.250.1', port=44818): # 实现它
        # 创建通讯客户端实例
        # self.client = modbus_tcp.TcpMaster(host=ip, port=port, timeout_in_sec=3.0)

        self.ip = ip
        self.port = port
        self.client = AllenBradleyNet(self.ip, self.port)


    def connect(self): # 实现它
        # 连接至PLC
        try:
            self.client.ConnectServer()
            print(f'client connect to EthIpHslClient {self.client}')
        except:
            print(traceback.format_exc())
        # print(f"客户端 是否连接到 plc服务端：{self.client.get_connected()}")

    def get_connected(self):
        # return self.client.get_connected()
        pass

    def read_int8(self, start=0, size=1): # 实现它

        res = self.client.ReadInt16(start, size)
        value = res.Content[0]
        return value

    def read_int16(self, start=0, size=2):  # 读int16
        pass

    def read_bool(self, start=0, size=1): # 读bool
        pass

    def read_real(self, start=0, size=4): # 读实数
        pass

    def write_int8(self, start=0, data_int8=0): # 实现它
        self.client.WriteInt16(start, data_int8)

    def write_int16(self, start=0, data_int8=0): #
        pass

    def write_real(self, start=0, data_real=1.0): # 写实数  用于发送坐标等
        pass

    def write_bool(self, start=0, data_bool=False): # 写bool
        pass

    def read_string(self, start=0, size=50, dbnumber=0): # 实现它
        # res = self.client.ReadString('gstrProgramName', 20)
        res = self.client.ReadString(start, 1) # 20240725
        value = res.Content # '\x08\x0030008828'
        value = value[2:]
        return value

    def write_string(self, start=0, data_str='hello', dbnumber=0): # 实现它 todo

        # 自定义方法， 依次写入8个整数
        data_str = data_str[:len(start)] if len(data_str)>len(start) else data_str
        for ind, c in enumerate(data_str):
            c_int = ord(c) # 转为ascii码值
            self.client.WriteInt16(start[ind], c_int)
        print(f'write_string_user 字符串写入成功 {data_str}')


    def close(self): # 实现它
        self.client.ConnectClose()
        print(f"plc closed")
